package com.songlanyun.modules.rabbitmq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.modules.rabbitmq.entity.MsgLog;
import com.songlanyun.modules.rabbitmq.mapper.MsgLogMapper;
import com.songlanyun.modules.rabbitmq.service.MsgLogService;

import com.songlanyun.modules.rabbitmq.util.JodaTimeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service("msgLogService")
public class MsgLogServiceImpl extends ServiceImpl<MsgLogMapper, MsgLog> implements MsgLogService {

    @Resource
    private MsgLogMapper msgLogMapper;

    @Override
    public void updateStatus(String msgId, Integer status) {
        MsgLog msgLog = this.selectByMsgId(msgId);
        if (msgLog != null) {
            msgLog.setStatus(status);
            msgLog.setUpdateTime(new Date());
            this.msgLogMapper.updateById(msgLog);
        }

    }

    @Override
    public MsgLog selectByMsgId(String msgId) {
        return msgLogMapper.selectById(msgId);
    }

    @Override
    public List<MsgLog> selectTimeoutMsg() {
        QueryWrapper<MsgLog> wrapper = new QueryWrapper<>();
        wrapper.ge("next_try_time", new Date());
        wrapper.ge("status", 0);
        return msgLogMapper.selectList(wrapper);
    }

    @Override
    public void updateTryCount(String msgId, Date tryTime) {
        Date nextTryTime = JodaTimeUtil.plusMinutes(tryTime, 1);
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setNextTryTime(nextTryTime);
        msgLogMapper.updateById(msgLog);
    }

    @Override
    @Transactional
    public void saveMsgLog(String msgId, Integer status, String receivedExchange, String receivedRoutingKey,String msg) {
        MsgLog msgLog = new MsgLog();
        msgLog.setMsgId(msgId);
        msgLog.setMsg(msg);
        msgLog.setStatus(status);
        msgLog.setExchange(receivedExchange);
        msgLog.setRoutingKey(receivedRoutingKey);
        msgLog.setCreateTime(new Date());
        msgLog.setUpdateTime(new Date());
        msgLogMapper.insert(msgLog);
    }


}
